package yzbx.personalwebsite.tool;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * {@code @Author} zxm
 * {@code @Description} 杂项工具类
 * {@code @Date} 2024/10/09/09:31
 * {@code @Version} 1.0
 */
public class utilTool {

    private static final Logger LOGGER = LoggerFactory.getLogger(utilTool.class);

    public static String md5(String plainString) {
        if (plainString == null) {
            plainString = "";
        }
        String salt1 = "yzbx";
        String salt2 = "12138";
        String confound = salt1 + plainString + salt2;
        return DigestUtils.md5DigestAsHex(confound.getBytes(StandardCharsets.UTF_8));
    }

    public static String getRandomId(int num) {
        String CHARACTERS = "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";

        Random random = new Random();
        StringBuilder randomStr = new StringBuilder();
        for (int i = 0; i < num; i++) {
            randomStr.append(CHARACTERS.charAt(random.nextInt(CHARACTERS.length())));
        }
        return randomStr.toString();
    }

    public static void saveImg(MultipartFile file, String filePath, String fileName) {

        String targetPath = filePath + fileName;
        LOGGER.info("新增图片路径：{}", targetPath);
        try {
            file.transferTo(new File(targetPath));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String getNowTime() {
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd HHmmss");
        return now.format(formatter);
    }

    public static String getNowTime(String pattern) {
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        return now.format(formatter);
    }

    /**
     * 合并JSON对象，用source覆盖target，返回覆盖后的JSON对象。
     *
     * @param source JSONObject
     * @param target JSONObject
     * @return JSONObject
     */
    public static JSONObject jsonMerge(JSONObject source, JSONObject target) {
        // 覆盖目标JSON为空，直接返回覆盖源
        if (target == null) {
            return source;
        }

        for (String key : source.keySet()) {
            Object value = source.get(key);
            if (!target.containsKey(key)) {
                target.put(key, value);
            } else {
                if (value instanceof JSONObject) {
                    JSONObject valueJson = (JSONObject) value;
                    JSONObject targetValue = jsonMerge(valueJson, target.getJSONObject(key));
                    target.put(key, targetValue);
                } else if (value instanceof JSONArray) {
                    JSONArray valueArray = (JSONArray) value;
                    for (int i = 0; i < valueArray.size(); i++) {
                        JSONObject obj = (JSONObject) valueArray.get(i);
                        JSONObject targetValue = jsonMerge(obj, (JSONObject) target.getJSONArray(key).get(i));
                        target.getJSONArray(key).set(i, targetValue);
                    }
                } else {
                    target.put(key, value);
                }
            }
        }
        return target;
    }

    public static String decomposeDateRange(String dateRange) throws ParseException {
        String[] parts = dateRange.split("-");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

        Date startDate = sdf.parse(parts[0]);
        Date endDate = sdf.parse(parts[1]);

        List<String> dateList = new ArrayList<>();

        // Adding the first date
        dateList.add(sdf.format(startDate));

        // Adding the intermediate dates
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDate);

        while (!calendar.getTime().equals(endDate)) {
            calendar.add(Calendar.DAY_OF_YEAR, 1);  // Increment by one day
            dateList.add(sdf.format(calendar.getTime()));

            // Break if endDate is before startDate (assuming incorrect range was provided)
            if (calendar.getTime().after(endDate)) {
                break;
            }
        }

        // Adding the last date

        StringBuilder rDate = new StringBuilder();
        for (String date : dateList) {
            rDate.append(date).append(",");
        }
        rDate.deleteCharAt(rDate.length() - 1);
        return rDate.toString();
    }

    public static void main(String[] args) {
        //System.out.println(md5(""));

        //System.out.println(getRandomId(16));

//        Map<String, Object> m = new HashMap<>();
//        m.put("1", "11");
//        m.put("2", "new Date()");
//        System.out.println(m.get("3"));


//        JSONObject json = new JSONObject();
//        String a = json.getString("q");
//        System.out.println(json.getString("q"));

        try {
            System.out.println(decomposeDateRange("20200506-20200508"));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }

    }
}
